﻿using System;
using System.Runtime.InteropServices;

namespace InfoPathHelpers.Win32
{
    public class NetApi32
    {
        const int NERR_Success = 0;

        [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int NetGetJoinInformation(
            string lpServer,
            out IntPtr lpNameBuffer,
            out NET_API_STATUS bufferType);

        [DllImport("Netapi32.dll")]
        private static extern int NetApiBufferFree(IntPtr Buffer);

        public enum NET_API_STATUS
        {
            NetSetupUnknownStatus = 0,
            NetSetupUnjoined,
            NetSetupWorkgroupName,
            NetSetupDomainName
        }

        public static NetAPIJoinInfo GetNetAPIJoinInfo()
        {
            var Result = 0;
            var Buffer = IntPtr.Zero;
            var NetworkName = string.Empty;
            var Status = NET_API_STATUS.NetSetupUnknownStatus;

            try
            {
                Result = NetGetJoinInformation(null, out Buffer, out Status);
                if (Result == NERR_Success)
                {
                    NetworkName = Marshal.PtrToStringAuto(Buffer) ?? string.Empty;
                }
            }
            finally
            {
                if (Buffer != IntPtr.Zero)
                {
                    NetApiBufferFree(Buffer);
                }
            }
            return new NetAPIJoinInfo(NetworkName, Status == NET_API_STATUS.NetSetupDomainName);
        }

        public class NetAPIJoinInfo
        {
            public NetAPIJoinInfo(string networkName, bool isDomainJoined)
            {
                NetworkName = networkName;
                IsDomainJoined = isDomainJoined;
            }

            public string NetworkName { get; private set; }
            public bool IsDomainJoined { get; private set; }
        }
    }
}
